package com.mission.schedule.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.CommonDialog.LocalSynServiceDialog;
import com.mission.schedule.CommonDialog.ServerDataDownLocalServiceDialog;
import com.mission.schedule.R;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.BackgroundBean;
import com.mission.schedule.bean.MyMessageBackBean;
import com.mission.schedule.bean.MyMessageBean;
import com.mission.schedule.bean.NoteTypeBean;
import com.mission.schedule.bean.SuccessOrFailBean;
import com.mission.schedule.bean.qd606.NoteTitleDetailBean;
import com.mission.schedule.clock.WriteAlarmClock;
import com.mission.schedule.constants.Const;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.cutimage.Crop;
import com.mission.schedule.cutimage.Log;
import com.mission.schedule.fragment.BaseFragment;
import com.mission.schedule.my160920.widget.CircleImageView;
import com.mission.schedule.service.DownAPKService;
import com.mission.schedule.service.DownImageService;
import com.mission.schedule.utils.ActivityManager1;
import com.mission.schedule.utils.AfterPermissionGranted;
import com.mission.schedule.utils.EasyPermissions;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.PathFromUriUtils;
import com.mission.schedule.utils.PhotoActionHelper;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.RxPhotoUtils;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.StringUtils;
import com.mission.schedule.utils.UiUtils;
import com.mission.schedule.utils.Utils;
import com.mission.schedule.view.noteeditscroll.OverScrollView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by liwei on 2017/10/20.
 */

public class NewMyAppSetActivity extends Activity implements View.OnClickListener, EasyPermissions.PermissionCallbacks {

    CircleImageView image_img;
    TextView tv_memberlogin, tixingname_tv;// , notification_tv
    TextView tixing_btn, help_btn;
    ImageView member_relative;
    RelativeLayout tixing_ll, jifenduihuan_btn_ll;
    String untaskend;
    Bitmap backgroundbitmap = null;
    TextView exit_btn, title;
    RelativeLayout my_ll_top;

    static App app = App.getDBcApplication();

    String userId, backgroundname;
    /**
     * 屏幕的宽度
     */
    protected int mScreenWidth;
    /**
     * 屏幕的高度
     */
    protected int mScreenHeight;
    private String paths;

    private ImageLoader imageLoader;
    private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
    private DisplayImageOptions options;
    String path;
    private String mOutputPath;
    private String mDemoPath;


    private TextView setbackground_tv;// 设置背景
    private RelativeLayout rl1;// 默认铃声
    private TextView ringname_tv;
    private TextView morenbeforetime_tv;// 默认提前提醒时间
    private TextView morenbeforeday_tv;// 默认到期日提醒时间
    private TextView everydaywenhou_tv;// 每天问候
    private TextView alldaytixing_tv;// 全天的提醒时间
    private TextView yijianfankui_tv;// 意见反馈
    private TextView haoping_tv;// 好评
    private TextView aboutus_tv;// 关于我们
    private TextView setendsound_tv;
    private TextView common_set;//常用设置
    private TextView updatedata_tv, set_ls_btn,myfriend;
    private ToggleButton toggle_notifation;
    private RelativeLayout sun_rel, cylxr_btn_ll, todayend_ll, jifenqiandao_btn_ll, status_bar_image, vip_ll;
    private OverScrollView scoll;
    private LinearLayout ll2;
    private LinearLayout jf_ll;
    private ImageView tup;

    private TextView status_bar_text, vip_text, vip_remark, tv_remarklogin, jifen_today, before_time, sun_text, everyday_tv, allday_time, end_tv, zongjifen, daoqiri, hidden_tv, udpateapp_tv;

    Context context;
    // private final static int STATE_CHOOSE = 1;// 状态选择
    private static final int CHOOSE_MUSIC = 2;// 选择铃声
    private static final int BEFORETIME = 3;// 提前时间设置

    String ringcode;// 铃声对应的编码

    SharedPrefUtil sharedPrefUtil = null;
    String ringname;
    String beforetime;
    String qdrbefore_time;
    String isYouKe = "1";

    boolean isnotification = true;
    String notificationStr = "";
    ActivityManager1 activityManager = null;
    boolean isShow = false;
    File outfile;
    HeadImageBackReceiver headImageBackReceiver;
    LinearLayout top_ll_left;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appset);
        activityManager = ActivityManager1.getInstance();
        activityManager.addActivities(this);
        try {
            DisplayMetrics metric = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metric);
            mScreenWidth = metric.widthPixels;
            mScreenHeight = metric.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }

        context = this;

        headImageBackReceiver = new HeadImageBackReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("headImageBackReceiver");
        registerReceiver(headImageBackReceiver, filter);


        imageLoader = ImageLoader.getInstance();
        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        backgroundname = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERBACKGROUNDPATH, "");
        userId = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "0");
        isYouKe = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, "1");
        if ("".equals(StringUtils.getIsStringEqulesNull(backgroundname))) {
            path = URLConstants.默认背景图片;
        } else {
            path = URLConstants.默认背景图片 + "=" + backgroundname;
        }

        ll2 = (LinearLayout) findViewById(R.id.ll2);
        cylxr_btn_ll = (RelativeLayout) findViewById(R.id.cylxr_btn_ll);
        jf_ll = (LinearLayout) findViewById(R.id.jf_ll);
        rl1 = (RelativeLayout) findViewById(R.id.rl1);
        my_ll_top = (RelativeLayout) findViewById(R.id.my_ll_top);
        sun_rel = (RelativeLayout) findViewById(R.id.sun_rel);
        scoll = (OverScrollView) findViewById(R.id.scoll);
        vip_ll = (RelativeLayout) findViewById(R.id.vip_ll);
        todayend_ll = (RelativeLayout) findViewById(R.id.todayend_ll);
        jifenqiandao_btn_ll = (RelativeLayout) findViewById(R.id.jifenqiandao_btn_ll);
        status_bar_image = (RelativeLayout) findViewById(R.id.status_bar_image);
        toggle_notifation = (ToggleButton) findViewById(R.id.toggle_notifation);
        setbackground_tv = (TextView) findViewById(R.id.setbackground_tv);
        ringname_tv = (TextView) findViewById(R.id.ringname_tv);
        morenbeforetime_tv = (TextView) findViewById(R.id.morenbeforetime_tv);
        morenbeforeday_tv = (TextView) findViewById(R.id.morenbeforeday_tv);
        everydaywenhou_tv = (TextView) findViewById(R.id.everydaywenhou_tv);
        alldaytixing_tv = (TextView) findViewById(R.id.alldaytixing_tv);
        yijianfankui_tv = (TextView) findViewById(R.id.yijianfankui_tv);
        haoping_tv = (TextView) findViewById(R.id.haoping_tv);
        aboutus_tv = (TextView) findViewById(R.id.aboutus_tv);
        setendsound_tv = (TextView) findViewById(R.id.setendsound_tv);
        updatedata_tv = (TextView) findViewById(R.id.updatedata_tv);
        status_bar_text = (TextView) findViewById(R.id.status_bar_text);
        jifen_today = (TextView) findViewById(R.id.jifen_today);
        before_time = (TextView) findViewById(R.id.before_time);
        sun_text = (TextView) findViewById(R.id.sun_text);
        everyday_tv = (TextView) findViewById(R.id.everyday_tv);
        allday_time = (TextView) findViewById(R.id.allday_time);
        end_tv = (TextView) findViewById(R.id.end_tv);
        tup = (ImageView) findViewById(R.id.tup);
        zongjifen = (TextView) findViewById(R.id.zongjifen);
        daoqiri = (TextView) findViewById(R.id.daoqiri);
        hidden_tv = (TextView) findViewById(R.id.hidden_tv);
        udpateapp_tv = (TextView) findViewById(R.id.udpateapp_tv);
        title = (TextView) findViewById(R.id.title);
        vip_remark = (TextView) findViewById(R.id.vip_remark);
        vip_text = (TextView) findViewById(R.id.vip_text);
        tv_remarklogin = (TextView) findViewById(R.id.tv_remarklogin);
        set_ls_btn = (TextView) findViewById(R.id.set_ls_btn);
        common_set = (TextView) findViewById(R.id.common_set);
        top_ll_left = (LinearLayout) findViewById(R.id.top_ll_left);
        top_ll_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        myfriend = (TextView) findViewById(R.id.myfriend);

        myfriend.setOnClickListener(this);
        common_set.setOnClickListener(this);
        vip_remark.setOnClickListener(this);
        vip_text.setOnClickListener(this);
        vip_ll.setOnClickListener(this);
        cylxr_btn_ll.setOnClickListener(this);
        ll2.setOnClickListener(this);
        jf_ll.setOnClickListener(this);
        rl1.setOnClickListener(this);
        sun_rel.setOnClickListener(this);
        scoll.setOnClickListener(this);
        todayend_ll.setOnClickListener(this);
        jifenqiandao_btn_ll.setOnClickListener(this);
        status_bar_image.setOnClickListener(this);
        status_bar_image.setOnClickListener(this);
        toggle_notifation.setOnClickListener(this);
        setbackground_tv.setOnClickListener(this);
        ringname_tv.setOnClickListener(this);
        morenbeforetime_tv.setOnClickListener(this);
        morenbeforeday_tv.setOnClickListener(this);
        everydaywenhou_tv.setOnClickListener(this);
        alldaytixing_tv.setOnClickListener(this);
        yijianfankui_tv.setOnClickListener(this);
        haoping_tv.setOnClickListener(this);
        aboutus_tv.setOnClickListener(this);
        setendsound_tv.setOnClickListener(this);
        updatedata_tv.setOnClickListener(this);
        status_bar_text.setOnClickListener(this);
        jifen_today.setOnClickListener(this);
        before_time.setOnClickListener(this);
        sun_text.setOnClickListener(this);
        everyday_tv.setOnClickListener(this);
        allday_time.setOnClickListener(this);
        end_tv.setOnClickListener(this);
        tup.setOnClickListener(this);
        zongjifen.setOnClickListener(this);
        daoqiri.setOnClickListener(this);
        hidden_tv.setOnClickListener(this);
        udpateapp_tv.setOnClickListener(this);
        set_ls_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent x = new Intent(context, WebViewActivity.class);
                x.putExtra("url", "http://www.keytimeapp.com/setup.html");
                x.putExtra("remark2","不提醒的解决办法");
                startActivity(x);
            }
        });

//        scoll.setScrollViewListener(new OverScrollView.ScrollViewListener() {
//            @Override
//            public void onScrollChanged(OverScrollView scrollView, int x, int y, int oldx, int oldy) {
//                int screenWidht = UiUtils.getScreenWidths(context) + 300;
//                int newHeight = UiUtils.dip2px(context, y);
//                float colorF = 0.001f;
//
//                if (newHeight == 0) {
//                    my_ll_top.setAlpha(0);
//                } else {
//                    if (newHeight >= screenWidht) {
//                        float alpha = (newHeight - screenWidht) * colorF;
//                        if (alpha <= 1) {
//                            my_ll_top.setAlpha(alpha);
//                        } else {
//                            my_ll_top.setAlpha(1);
//                        }
//                    }
//                }
//            }
//        });

        if (sharedPrefUtil.getString(context,
                ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            options = new DisplayImageOptions.Builder()
                    .showStubImage(R.mipmap.b1)
                    .showImageForEmptyUri(R.mipmap.b1)
                    .showImageOnFail(R.mipmap.b1).cacheInMemory(true)
                    .cacheOnDisc(true).cacheInMemory(true)
                    .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
                    .build();
        } else {
            options = new DisplayImageOptions.Builder()
                    .showStubImage(R.mipmap.turh)
                    .showImageForEmptyUri(R.mipmap.turh)
                    .showImageOnFail(R.mipmap.turh).cacheInMemory(true)
                    .cacheOnDisc(true).cacheInMemory(true)
                    .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
                    .build();
        }

        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.SHUNYANTYPE, "0") == null) {
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.SHUNYANTYPE, "0");
            sun_text.setText("关闭");
        } else {
            sun_text.setText(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.SHUNYANTYPE, "0").equals("0") ? "关闭" : "打开");
        }

        ringcode = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.MUSICCODE, "g_88");
        isYouKe = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, "1");
        beforetime = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.BEFORETIME, "0");
        qdrbefore_time = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.DQRBEFORETIME, "0");
        notificationStr = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNOTIFICATION, "0");
        if ("0".equals(notificationStr)) {
            status_bar_text.setText("显示");
        } else {
            status_bar_text.setText("隐藏");
        }

        untaskend = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "0");
        if ("0".equals(untaskend)) {
            hidden_tv.setText("隐藏");
        } else {
            hidden_tv.setText("显示");
        }

        member_relative = (ImageView) findViewById(R.id.member_relative);
        member_relative.setOnClickListener(this);
        image_img = (CircleImageView) findViewById(R.id.image_img);
        image_img.setOnClickListener(this);
        tv_memberlogin = (TextView) findViewById(R.id.tv_memberlogin);
        exit_btn = (TextView) findViewById(R.id.exit_btn);
        exit_btn.setOnClickListener(this);
        tixing_btn = (TextView) findViewById(R.id.tixing_btn);
        tixing_btn.setOnClickListener(this);
        help_btn = (TextView) findViewById(R.id.help_btn);
        help_btn.setOnClickListener(this);
        jifenduihuan_btn_ll = (RelativeLayout) findViewById(R.id.jifenduihuan_btn_ll);
        jifenduihuan_btn_ll.setOnClickListener(this);
        tixing_ll = (RelativeLayout) findViewById(R.id.tixing_ll);
        tixing_ll.setOnClickListener(this);
        tixingname_tv = (TextView) findViewById(R.id.tixingname_tv);

        String image_head = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERPHOTOPATH, "");
        String imageUrl = URLConstants.图片 + image_head + "&imageType=2&imageSizeType=3";
        int fsize = App.getDBcApplication().getAllNewFriendData(userId, false).size();
        myfriend.setText("我的好友"+(fsize == 0 ? "" : "("+fsize+")"));
        String dicr = Environment.getExternalStorageDirectory() + "/DCIM/";
        outfile = new File(dicr, "TimeApp");
        // 如果文件不存在，则创建一个新文件
        if (!outfile.isDirectory()) {
            try {
                outfile.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Bitmap bitmapHead = BitmapFactory.decodeFile(outfile + "/" + image_head.replace('/', '0'));
        Bitmap bitmapBG = BitmapFactory.decodeFile(outfile + "/" + backgroundname.replace('/', '0'));

        if (bitmapHead == null) {
            imageLoader.displayImage(imageUrl, image_img, options, animateFirstListener);
            Intent intent = new Intent(context, DownImageService.class);
            intent.setAction("downimage");
            intent.putExtra("url", imageUrl);
            intent.putExtra("name", image_head.replace('/', '0'));
            context.startService(intent);
        } else {
            image_img.setImageBitmap(bitmapHead);
        }

        if (bitmapBG == null) {
            imageLoader.displayImage(path, member_relative, options, animateFirstListener);
            Intent intent = new Intent(context, DownImageService.class);
            intent.setAction("downimage");
            intent.putExtra("url", path);
            intent.putExtra("name", backgroundname.replace('/', '0'));
            context.startService(intent);
        } else {
            member_relative.setImageBitmap(bitmapBG);
        }


        tv_memberlogin.setText(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""));
        title.setText(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""));
        String ringstate = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.RINGSTATE, "0");
        if (ringstate.equals("0")) {
            tixingname_tv.setText("语音");
            tixingname_tv.setTextColor(getResources().getColor(
                    R.color.mingtian_color));
            tixing_btn.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.set_ring_tx), null, null, null);
        } else if (ringstate.equals("1")) {
            tixingname_tv.setText("静音");
            tixingname_tv.setTextColor(getResources().getColor(
                    R.color.sunday_txt));
            tixing_btn.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.set_ring_jy), null, null, null);
        } else if (ringstate.equals("2")) {
            tixingname_tv.setText("短音");
            tixingname_tv.setTextColor(getResources().getColor(
                    R.color.mingtian_color));
            tixing_btn.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.set_ring_tx), null, null, null);
        } else if (ringstate.equals("3")) {
            tixingname_tv.setText("振动");
            tixingname_tv.setTextColor(getResources().getColor(
                    R.color.mingtian_color));
            tixing_btn.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.set_ring_zd), null, null, null);
        }

        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            vip_text.setText("正式用户");
            vip_text.setTextColor(getResources().getColor(R.color.setting_text_color));
            vip_remark.setVisibility(View.GONE);
            exit_btn.setVisibility(View.VISIBLE);
        } else {
            vip_text.setText("注册正式用户或登录");
            vip_text.setTextColor(getResources().getColor(R.color.newlogin_origin));
            vip_remark.setVisibility(View.VISIBLE);
            exit_btn.setVisibility(View.GONE);
        }
        String localpath = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOCALPATH, "1");
        if (localpath.length() > 1) {
            tup.setImageBitmap(BitmapFactory.decodeFile(localpath));
        } else {
            if ("0".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.aa1));
            } else if ("1".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.a1));
            } else if ("2".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.b1));
            } else if ("3".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.c1));
            } else if ("4".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.d1));
            } else if ("5".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.e1));
            } else if ("6".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.f1));
            } else if ("7".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.g1));
            } else if ("8".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.h1));
            }
        }
        String remark = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.PERSONREMARK, "");
        tv_remarklogin.setText(remark.isEmpty() ? "暂无信息" : remark);
        setHeadView();
    }


    @Override
    public void onResume() {
        super.onResume();
        String image_head = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERPHOTOPATH, "");
        String imageUrl = URLConstants.图片 + image_head + "&imageType=2&imageSizeType=3";
        tv_memberlogin.setText(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""));
        title.setText(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""));
        String dicr = Environment.getExternalStorageDirectory() + "/DCIM/";
        outfile = new File(dicr, "TimeApp");
        // 如果文件不存在，则创建一个新文件
        if (!outfile.isDirectory()) {
            try {
                outfile.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Bitmap bitmapHead = BitmapFactory.decodeFile(outfile + "/" + image_head.replace('/', '0'));

        if (bitmapHead == null) {
            imageLoader.displayImage(imageUrl, image_img, options, animateFirstListener);
            Intent intent = new Intent(context, DownImageService.class);
            intent.setAction("downimage");
            intent.putExtra("url", imageUrl);
            intent.putExtra("name", image_head.replace('/', '0'));
            context.startService(intent);
        } else {
            image_img.setImageBitmap(bitmapHead);
        }

        untaskend = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "0");
        if ("0".equals(untaskend)) {
            hidden_tv.setText("隐藏");
        } else {
            hidden_tv.setText("显示");
        }
        String jifen = app.todayJifen();
        jifen_today.setText("今日积分:" + jifen);
        String zjf = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ZJF, "0");
        zongjifen.setText("总积分:" + zjf);
        int before = Integer.valueOf(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.BEFORETIME, "0"));
        String before_str = "0分钟";
        if (before == 0) {
            before_str = "0分钟";
        } else if (before == 5) {
            before_str = "5分钟";
        } else if (before == 15) {
            before_str = "15分钟";
        } else if (before == 30) {
            before_str = "30分钟";
        } else if (before == 60) {
            before_str = "1小时";
        } else if (before == 120) {
            before_str = "2小时";
        } else if (before == 24 * 60) {
            before_str = "1天";
        } else if (before == 48 * 60) {
            before_str = "2天";
        } else if (before == 7 * 24 * 60) {
            before_str = "1周";
        }
        before_time.setText(before_str);

        int dqr = Integer.valueOf(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.DQRBEFORETIME, "0"));
        String dqr_str = "0天";
        if (dqr == 0) {
            dqr_str = "0天";
        } else if (dqr == 24 * 60) {
            dqr_str = "1天";
        } else if (dqr == 24 * 3 * 60) {
            dqr_str = "3天";
        } else if (dqr == 5 * 24 * 60) {
            dqr_str = "5天";
        } else if (dqr == 7 * 24 * 60) {
            dqr_str = "7天";
        } else if (dqr == 15 * 24 * 60) {
            dqr_str = "15天";
        }
        daoqiri.setText(dqr_str);

        ringname = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.MUSICDESC, "完成任务");
        ringname_tv.setText(ringname);

        String morTime = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.MORNINGTIME, "07:58");
        String nightTime = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.NIGHTTIME, "20:58");
        String morSta = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.MORNINGSTATE, "0");
        String nigSta = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.NIGHTSTATE, "0");
        if (morSta.equals("0") && nigSta.equals("0")) {
            everyday_tv.setText(morTime + " " + nightTime);
        } else if (morSta.equals("0") && nigSta.equals("1")) {
            everyday_tv.setText(morTime);
        } else if (morSta.equals("1") && nigSta.equals("0")) {
            everyday_tv.setText(nightTime);
        } else {
            everyday_tv.setText("无");
        }

        String alldaysta = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ALLSTATE, "0");
        String alldaytime = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ALLTIME, "23:59");
        if (alldaysta.equals("0")) {
            allday_time.setText(alldaytime);
        } else {
            allday_time.setText("无");
        }

        String duanyin = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ENDSOUNDSTATE, "0");
        String zhendong = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ENDWAKESTATE, "0");
        if (duanyin.equals("0") && zhendong.equals("0")) {
            end_tv.setText("短音 + 振动");
        } else if (duanyin.equals("0") && zhendong.equals("1")) {
            end_tv.setText("短音");
        } else if (duanyin.equals("1") && zhendong.equals("0")) {
            end_tv.setText("振动");
        } else {
            end_tv.setText("无");
        }
        String localpath = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOCALPATH, "1");
        if (localpath.length() > 1) {
            tup.setImageBitmap(BitmapFactory.decodeFile(localpath));
        } else {
            if ("0".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.aa1));
            } else if ("1".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.a1));
            } else if ("2".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.b1));
            } else if ("3".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.c1));
            } else if ("4".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.d1));
            } else if ("5".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.e1));
            } else if ("6".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.f1));
            } else if ("7".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.g1));
            } else if ("8".equals(localpath)) {
                tup.setBackground(context.getResources().getDrawable(R.mipmap.h1));
            }
        }
        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            vip_text.setText("正式用户");
            vip_text.setTextColor(getResources().getColor(R.color.setting_text_color));
            vip_remark.setVisibility(View.GONE);
            exit_btn.setVisibility(View.VISIBLE);
        } else {
            vip_text.setText("注册正式用户或登录");
            vip_text.setTextColor(getResources().getColor(R.color.newlogin_origin));
            vip_remark.setVisibility(View.VISIBLE);
            exit_btn.setVisibility(View.GONE);
        }
        String remark = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.PERSONREMARK, "");
        tv_remarklogin.setText(remark.isEmpty() ? "暂无信息" : remark);

    }

    private void setHeadView() {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) member_relative.getLayoutParams();
        params.height = mScreenWidth;
        member_relative.setLayoutParams(params);
        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) image_img.getLayoutParams();
        params2.topMargin = mScreenWidth - Utils.dipTopx(context, 45);
        image_img.setLayoutParams(params2);
        RelativeLayout.LayoutParams params3 = (RelativeLayout.LayoutParams) tv_memberlogin.getLayoutParams();
        params3.topMargin = mScreenWidth - Utils.dipTopx(context, 25);
        tv_memberlogin.setLayoutParams(params3);
        RelativeLayout.LayoutParams params4 = (RelativeLayout.LayoutParams) tv_remarklogin.getLayoutParams();
        params4.topMargin = mScreenWidth + Utils.dipTopx(context, 5);
        tv_remarklogin.setLayoutParams(params4);

        scoll.post(new Runnable() {
            @Override
            public void run() {
                scoll.scrollTo(0, mScreenWidth / 4);
            }
        });
    }


    @Override
    public void onClick(View v) {
        SharedPrefUtil sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        Intent intent;
        switch (v.getId()) {
            case R.id.myfriend:
                startActivity(new Intent(context, NewMyFriendActivity.class));
                break;
            case R.id.udpateapp_tv:
                getAPPVersion();
                break;
            case R.id.status_bar_image:
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNOTIFICATION, "0").equals("1")) {
                    // 选中
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISNOTIFICATION, "0");
                    status_bar_text.setText("显示");
                } else {
                    // 未选中
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISNOTIFICATION, "1");
                    status_bar_text.setText("隐藏");
                }
                break;
            case R.id.ll2:
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
                    xiufudatadialog();
                } else {
                    Intent newt = new Intent(context, PhoneCodeLoginActivity.class);
                    newt.putExtra("type", 1);
                    newt.putExtra("login", true);
                    context.startActivity(newt);
                }
                break;
            case R.id.sun_rel:
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE,
                        ShareFile.SHUNYANTYPE, "0").equals("0")) {
                    sharedPrefUtil.putString(context, ShareFile.USERFILE,
                            ShareFile.SHUNYANTYPE, "1");
                    sun_text.setText("打开");
                } else {
                    sharedPrefUtil.putString(context, ShareFile.USERFILE,
                            ShareFile.SHUNYANTYPE, "0");
                    sun_text.setText("关闭");
                }
                break;
            case R.id.common_set:
                startActivity(new Intent(context, AppSetActivity.class));
                break;
            case R.id.vip_remark:
            case R.id.vip_text:
            case R.id.vip_ll:
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
                    startActivity(new Intent(context, AboutUsActivity.class));
                } else {
                    Intent newt = new Intent(context, PhoneCodeLoginActivity.class);
                    newt.putExtra("type", 1);
                    newt.putExtra("login", true);
                    context.startActivity(newt);
                }
                break;
            case R.id.cylxr_btn_ll:
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
                    Intent zhuanfa = new Intent(context, NewFriendsActivity.class);
                    zhuanfa.putExtra("titleid", "00");
                    startActivity(zhuanfa);
                } else {
                    VipDailog();
                }
                break;
            case R.id.jifenqiandao_btn_ll:
                Toast.makeText(context,"积分签到升级中,敬请期待",Toast.LENGTH_LONG).show();
//                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
//                    startActivity(new Intent(context, LocalQiandaoActivity.class));
//                } else {
//                    Intent newt = new Intent(context, PhoneCodeLoginActivity.class);
//                    newt.putExtra("type", 1);
//                    newt.putExtra("login", true);
//                    context.startActivity(newt);
//                }

                break;
            case R.id.member_relative:
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
                    // 更换左边菜单的背景图
                    dialogShow();
                } else {
                    VipDailog();
                }
                break;
            case R.id.image_img:
                // 点击头像进入到个人详细信息
                if ("1".equals(isYouKe)) {
                    startActivity(new Intent(context, PersonMessageActivity.class));
                } else {
                    VipDailog();
                }
                break;
            case R.id.jifenduihuan_btn_ll:// 积分兑换
                if (sharedPrefUtil.getString(context,
                        ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
                    startActivity(new Intent(context, JiFenDuiHuanActivity.class));
                } else {
                    Intent newt = new Intent(context, PhoneCodeLoginActivity.class);
                    newt.putExtra("type", 1);
                    newt.putExtra("login", true);
                    context.startActivity(newt);
                }
                break;
            case R.id.exit_btn:
                try {
                    if ("1".equals(isYouKe)) {
                        List<Map<String, String>> unSchUpdateList = app.queryAllSchData(-1, 0, 0);
                        List<Map<String, String>> unRepUpdateList = app.QueryAllChongFuData(2);
                        List<NoteTitleDetailBean.TDelListBean> tDelListBeanArrayList = app.getAllNoteTitlesData(userId, true);
                        List<NoteTitleDetailBean.ListBean> listBeanList = app.getAllNoteDetailData(userId, true);
                        List<NewFriendsActivity.newFriendBean.PageBean.ItemsBean> itemsBeanList = app.getAllNewFriendData(userId, true);
                        List<NoteTypeBean.ListBean> typelist = app.getAllNoteTypeData(userId, true);
                        if ((unSchUpdateList != null && unSchUpdateList.size() > 0) || (unRepUpdateList != null && unRepUpdateList.size() > 0)
                                || (tDelListBeanArrayList != null && tDelListBeanArrayList.size() > 0) || (listBeanList != null && listBeanList.size() > 0)
                                || (itemsBeanList != null && itemsBeanList.size() > 0) || (typelist != null && typelist.size() > 0)) {
//                            startActivity(new Intent(context, ExitAlterActivity.class));
                            ExitDailog();
                        } else {
                            clearApp();
                            Intent newt = new Intent(context, PhoneCodeLoginNewActivity.class);
                            newt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            newt.putExtra("type", 0);
                            newt.putExtra("login", true);
                            context.startActivity(newt);
                        }
                    } else {
                        startActivity(new Intent(context, LogoutActivity.class));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.tixing_ll: // 提醒模式
                alterRingDialog();
                break;
            case R.id.help_btn:
                Intent intenth = new Intent(context, NoteOtherListActivity.class);
                intenth.putExtra("name", "常见问题");
                intenth.putExtra("puid", "5001");
                startActivity(intenth);
//                startActivity(new Intent(context, HelpActivity.class));
                break;
            case R.id.tixing_btn: // 提醒模式
                alterRingDialog();
                break;
            case R.id.todayend_ll:
                untaskend = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "0");
                if ("0".equals(untaskend)) {
                    hidden_tv.setText("显示");
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "1");
                } else {
                    hidden_tv.setText("隐藏");
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "0");
                }
                Intent intentmain = new Intent(Const.SHUAXINDATA);
                intentmain.putExtra("data", "success");
                intentmain.putExtra("index", 1);
                intentmain.putExtra("what", 2);
                context.sendBroadcast(intentmain);
                Intent intent_app1 = new Intent();
                intent_app1.setAction("appwidget");
                intent_app1.putExtra("aappwidget1", true);
                context.sendBroadcast(intent_app1);
                break;
            case R.id.updatedata_tv:
                cancleDialog();
                break;
            case R.id.top_ll_back:
                break;
            case R.id.personmessage_tv:// 个人信息
                if ("1".equals(isYouKe)) {
                    startActivityForResult(new Intent(context, PersonMessageActivity.class), 999);
                } else {
                    Intent newt = new Intent(context, PhoneCodeLoginActivity.class);
                    newt.putExtra("type", 1);
                    newt.putExtra("login", true);
                    context.startActivity(newt);
                }
                break;
            case R.id.setbackground_tv:// 设置背景
                startActivityForResult(new Intent(context, SetBackgroundActivity.class), 999);
                break;
            case R.id.rl1:// 默认铃声
                intent = new Intent(context, LingShengActivity.class);
                intent.putExtra("schID", "");
                startActivityForResult(intent, CHOOSE_MUSIC);
                break;
            case R.id.ringname_tv:// 默认铃声
                intent = new Intent(context, LingShengActivity.class);
                intent.putExtra("schID", "");
                startActivityForResult(intent, CHOOSE_MUSIC);
                break;
            case R.id.morenbeforetime_tv:// 默认提前提醒时间""
                intent = new Intent(context, SetBeforeTimeActivity.class);
                intent.putExtra("time", beforetime);
                intent.putExtra("type", "time");
                startActivityForResult(intent, BEFORETIME);
                break;
            case R.id.morenbeforeday_tv:// 默认到期日提前前天
                intent = new Intent(context, SetBeforeTimeActivity.class);
                intent.putExtra("time", qdrbefore_time);
                intent.putExtra("type", "day");
                startActivityForResult(intent, BEFORETIME);
                break;
            case R.id.everydaywenhou_tv:// 每天问候时间
                startActivity(new Intent(context, EverydayTimeActivity.class));
                break;
            case R.id.alldaytixing_tv:// 全天的提醒时间
                startActivity(new Intent(context, AllDayTimeActivity.class));
                break;
            case R.id.yijianfankui_tv:// 意见反馈
                startActivity(new Intent(context, OpinionBackActivity.class));
                break;
            case R.id.haoping_tv:// 给个好评
                try {
                    Intent intent1 = new Intent(Intent.ACTION_VIEW);
                    intent1.setData(Uri.parse("market://details?id=" + context.getPackageName()));
                    startActivity(intent1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.aboutus_tv:// 关于我们
                startActivity(new Intent(context, AboutUsActivity.class));
                break;
            case R.id.setendsound_tv:// 设置结束的音效
                startActivity(new Intent(context, EndSoundActivity.class));
                break;
            default:
                break;
        }
    }


    private void getAPPVersion() {
        final ProgressUtil progressUtil = new ProgressUtil();
        progressUtil.ShowProgress(context, true, true, "版本检测...");
        HttpUtils httpUtils = new HttpUtils(5000);
        httpUtils.send(HttpMethod.POST, URLConstants.获取最新版本号, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    Gson gson = new Gson();
                    MainActivity.AppVersionBean appversionbean = gson.fromJson(responseInfo.result, MainActivity.AppVersionBean.class);
                    if (appversionbean.status == 0) {
                        List<MainActivity.AppVersionBean.ListBean> list = appversionbean.list;
                        if (list != null) {
                            for (MainActivity.AppVersionBean.ListBean bean : list) {
                                if (Integer.valueOf(bean.android) > getVersionCode(Integer.valueOf(bean.android))) {
                                    updateApp(bean.android);
                                } else {
                                    Toast.makeText(context, "当前版本为最新版", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    }
                }
                progressUtil.dismiss();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                progressUtil.dismiss();
            }
        });
    }

    public int getVersionCode(int code) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            int version = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return code;
        }
    }

    private void updateApp(final String version) {
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.setCancelable(false);
        builder.show();
        Window window = builder.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_alter);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);
        TextView cancle_tv = (TextView) window.findViewById(R.id.cancle_tv);
        cancle_tv.setText("暂不更新");
        cancle_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        delete_tv.setText("已有新版本，请下载更新！");
        delete_ok.setText("立即更新");
        delete_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
                Intent intent = new Intent(context, DownAPKService.class);
                intent.setAction("DownAPK");
                context.startService(intent);
            }
        });
    }

    private void ExitDailog() {
        final AlertDialog builder = new AlertDialog.Builder(context).create();

        builder.show();
        Window window = builder.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_alter);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        delete_ok.setText("上传数据");
        delete_ok.setTextColor(Color.RED);
        delete_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (NetUtil.getConnectState(context) != NetUtil.NetWorkState.NONE) {
                    LocalSynServiceDialog localSynServiceDialog = new LocalSynServiceDialog(context, R.style.dialog_translucent, getWindowManager());
                    localSynServiceDialog.show();
                    localSynServiceDialog.setCallBack(new LocalSynServiceDialog.CallBack() {
                        @Override
                        public void dialogDismiss() {
                            clearApp();
                            Intent newt = new Intent(context, PhoneCodeLoginNewActivity.class);
                            newt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            newt.putExtra("type", 0);
                            newt.putExtra("login", true);
                            context.startActivity(newt);
                        }
                    });
                } else {
                    Toast.makeText(context, "请检查您的网络!", Toast.LENGTH_LONG).show();
                }
                builder.dismiss();
            }
        });
        TextView cancle_tv = (TextView) window.findViewById(R.id.cancle_tv);
        cancle_tv.setText("继续退出");
        cancle_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
                clearApp();
                Intent newt = new Intent(context, PhoneCodeLoginNewActivity.class);
                newt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                newt.putExtra("type", 0);
                newt.putExtra("login", true);
                context.startActivity(newt);
            }
        });
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);


        delete_tv.setText("本地还有未同步的数据，如果继续切换，数据将会丢失。请您在网络畅通的环境，先上传数据，再切换账号。");

    }

    private void clearApp() {
        WriteAlarmClock.clearAlarmClock(context);
        if (!"".equals(sharedPrefUtil.getString(context,
                ShareFile.USERFILE, ShareFile.TELEPHONE, ""))) {
            sharedPrefUtil.putString(context, ShareFile.USERFILE,
                    ShareFile.TELEPHONE, "");
        } else {
            sharedPrefUtil.putString(context, ShareFile.USERFILE,
                    ShareFile.USEREMAIL, "");
        }
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.WELCOMETOLOGIN, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ZDTX, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ZDTX, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.BDTX, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISTX, "1");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.QIANDAOSTRING, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.ISADMIN, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.USERID, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.USERNAME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.USERBACKGROUNDPATH, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.USERPHOTOPATH, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.USERSTATE, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.FIRSTLOGIN, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.U_ACC_NO, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.MAXFOCUSID, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.OUTWEEKFAG, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.UPDATESETTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.UPDATENOTESETTIME, "2017-01-01%2B00:00:00");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.DOWNSCHTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.DOWNREPTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.RINGSTATE, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.ISYOUKE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.DOWNTAGDATE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.OPENSTYLESTATE, "2");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.FRIENDDOWNSCHTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.FRIENDDOWNRepTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.FRIENDDOWNOldTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.PUSH_ALIAS, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.REFRESHFRIEND, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.FIRSTDOWNFOCUSSCH, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.SHOUCANGDATA, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.DOWNNEWFOCUSSHARESCHDATE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.DOWNNEWFOCUSSHAREREPDATE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.KuaiJieSouSuo, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.SHAREDATA, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.LOCALPATH, "1");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.ISSJMOSTIMAGE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.CUSTIOMMOSTIMAGE1, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.CUSTIOMMOSTIMAGE2, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.CUSTIOMMOSTIMAGE3, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.CUSTIOMMOSTIMAGE4, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.CUSTIOMMOSTIMAGE5, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.CUSTIOMMOSTIMAGE6, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.CUSTIOMMOSTIMAGE7, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.DQRBEFORETIME, "4320");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.ZJF, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.UNTASKEND, "1");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.PERSONREMARK, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.PERSONDOWNTIME, "2016-01-01%2B00:00:00");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.ISNEWYOUKE, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.WEEKCOLOR1, "2");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.MONTHCOLOR2, "3");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.YEARCOLOR3, "4");
        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                ShareFile.DOWNTASKTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISMOSTIMAGE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.MORNINGTIME, "07:58");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.NIGHTTIME, "20:58");
        ClearMAC();
        // RuntimeCmdManager.clearAppUserData(getPackageName());
        /**
         *
         */
        App.getDBcApplication().douleClear();
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.PERSONDOWNTIME, "2016-01-01");
        Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        Bundle extras = new Bundle();
        intentappwidget.putExtras(extras);
        context.sendBroadcast(intentappwidget);
        activityManager.doAllActivityFinish();
        finish();
    }

    private void VipDailog() {
        final AlertDialog builder = new AlertDialog.Builder(context).create();

        builder.show();
        Window window = builder.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_alter);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        delete_ok.setText("注册");
        delete_ok.setTextColor(Color.RED);
        delete_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.dismiss();
                Intent newt = new Intent(context, PhoneCodeLoginActivity.class);
                newt.putExtra("type", 1);
                newt.putExtra("login", true);
                context.startActivity(newt);
            }
        });
        TextView cancle_tv = (TextView) window.findViewById(R.id.cancle_tv);
        cancle_tv.setText("忽略");
        cancle_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);


        delete_tv.setText("该功能是正式用户功能\n请注册正式用户");

    }

    private void exitDailog() {
        final AlertDialog builder = new AlertDialog.Builder(context).create();

        builder.show();
        Window window = builder.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_alter);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        delete_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent newt = new Intent(context, PhoneCodeLoginNewActivity.class);
                newt.putExtra("type", 0);
                newt.putExtra("login", true);
                context.startActivity(newt);
                builder.dismiss();
            }
        });
        window.findViewById(R.id.cancle_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);

        delete_tv.setText("确定退出时间表!");

    }

    private void xiufudatadialog() {
        final Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_appset_shujuxiufu, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();

        more_pop_menu.findViewById(R.id.local).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                try {
                    if (app.QueryAllChongFuData(2).size() == 0 && app.queryAllSchData(-1, 0, 0).size() == 0 &&
                            App.getDBcApplication().getAllNoteTitlesData(userId, true).size() == 0 &&
                            App.getDBcApplication().getAllNoteDetailData(userId, true).size() == 0 &&
                            App.getDBcApplication().getAllNewFriendData(userId, true).size() == 0) {
                        Toast.makeText(context, "没有数据可以修复", Toast.LENGTH_SHORT).show();
                    } else {
                        LocalSynServiceDialog localSynServiceDialog = new LocalSynServiceDialog(context, R.style.dialog_translucent, getWindowManager());
                        localSynServiceDialog.show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        more_pop_menu.findViewById(R.id.network).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                ServerDataDownLocalServiceDialog serverDataDownLocalServiceDialog = new ServerDataDownLocalServiceDialog(context, R.style.dialog_translucent, getWindowManager());
                serverDataDownLocalServiceDialog.show();
            }
        });
        more_pop_menu.findViewById(R.id.canel_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

    }

    /**
     * 设置提醒模式
     */
    private void alterRingDialog() {
        Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_setyuyin, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();

        new alterRingDialogOnClick(dialog, more_pop_menu);
    }

    class alterRingDialogOnClick implements View.OnClickListener {

        private View view;
        private Dialog dialog;
        private TextView yuyin_tv;
        private TextView jingyin_tv;
        private TextView duanyin_tv;
        private TextView zd_tv;
        private TextView canel_tv;

        @SuppressLint("NewApi")
        public alterRingDialogOnClick(Dialog dialog, View view) {
            this.dialog = dialog;
            this.view = view;
            initview();
        }

        private void initview() {
            yuyin_tv = (TextView) view.findViewById(R.id.yuyin_tv);
            yuyin_tv.setOnClickListener(this);
            zd_tv = (TextView) view.findViewById(R.id.zd_tv);
            zd_tv.setOnClickListener(this);
            jingyin_tv = (TextView) view.findViewById(R.id.jingyin_tv);
            jingyin_tv.setOnClickListener(this);
            duanyin_tv = (TextView) view.findViewById(R.id.duanyin_tv);
            duanyin_tv.setOnClickListener(this);
            canel_tv = (TextView) view.findViewById(R.id.canel_tv);
            canel_tv.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.yuyin_tv:
                    sharedPrefUtil.putString(context, ShareFile.USERFILE,
                            ShareFile.RINGSTATE, "0");
                    tixingname_tv.setText("语音");
                    tixingname_tv.setTextColor(getResources().getColor(
                            R.color.mingtian_color));
                    tixing_btn.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.set_ring_tx), null, null, null);
                    dialog.dismiss();
                    break;
                case R.id.jingyin_tv:
                    sharedPrefUtil.putString(context, ShareFile.USERFILE,
                            ShareFile.RINGSTATE, "1");
                    tixingname_tv.setText("静音");
                    tixingname_tv.setTextColor(getResources().getColor(
                            R.color.sunday_txt));
                    tixing_btn.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.set_ring_jy), null, null, null);
                    dialog.dismiss();
                    break;
                case R.id.duanyin_tv:
                    sharedPrefUtil.putString(context, ShareFile.USERFILE,
                            ShareFile.RINGSTATE, "2");
                    tixingname_tv.setText("短音");
                    tixingname_tv.setTextColor(getResources().getColor(
                            R.color.mingtian_color));
                    tixing_btn.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.set_ring_tx), null, null, null);
                    dialog.dismiss();
                    break;
                case R.id.zd_tv:
                    sharedPrefUtil.putString(context, ShareFile.USERFILE,
                            ShareFile.RINGSTATE, "3");
                    tixingname_tv.setText("振动");
                    tixingname_tv.setTextColor(getResources().getColor(
                            R.color.mingtian_color));
                    tixing_btn.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.set_ring_zd), null, null, null);
                    dialog.dismiss();
                    break;
                case R.id.canel_tv:
                    dialog.dismiss();
                    break;
            }
        }
    }

    private void ClearMAC() {
        if (NetUtil.getConnectState(context) != NetUtil.NetWorkState.NONE) {
            if (sharedPrefUtil.getString(context,
                    ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
                final String path = URLConstants.修改MAC地址 + userId + "&uClintAddr="
                        + "" + "&uTocode=android";
                StringRequest request = new StringRequest(Request.Method.GET, path,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {

                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                    }
                });
                request.setTag("down");
                request.setRetryPolicy(new DefaultRetryPolicy(20000, 1, 1.0f));
                App.getHttpQueues().add(request);
            }
        } else {
            return;
        }
    }


    private void dialogShow() {
        Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac
                .inflate(R.layout.dialog_selecttypecamera, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();

        new MyClickClass(more_pop_menu, dialog);
    }

    class MyClickClass implements View.OnClickListener {

        private Dialog dialog;
        private Button dialog_button_photo;
        // private Button dialog_button_moren;
        private Button dialog_button_cancel;

        public MyClickClass(View view, Dialog dialog) {
            this.dialog = dialog;
            dialog_button_photo = (Button) view
                    .findViewById(R.id.dialog_button_photo);
            dialog_button_photo.setOnClickListener(this);
            // dialog_button_moren = (Button) view
            // .findViewById(R.id.dialog_button_moren);
            // dialog_button_moren.setOnClickListener(this);
            dialog_button_cancel = (Button) view
                    .findViewById(R.id.dialog_button_cancel);
            dialog_button_cancel.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            // Intent intent = null;
            switch (v.getId()) {
                case R.id.dialog_button_photo:
                    // ImageCutUtils.openLocalImage(MainActivity.this);
//				ImageCutTools.getInstance().selectPicture();
                    checkPhonePermission();
                    if (autoFag) {
//                        Crop.pickImage(NewMyFragment.this);
                        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(intent, 5002);
                    } else {
                        Toast.makeText(context, "权限已禁止访问!", Toast.LENGTH_LONG).show();
                    }

                    break;
                case R.id.dialog_button_cancel:
                    break;
            }
            dialog.dismiss();
        }
    }

    boolean autoFag = false;
    private static final int RC_LOCATION_CONTACTS_PERM = 124;

    @AfterPermissionGranted(RC_LOCATION_CONTACTS_PERM)
    private void checkPhonePermission() {
        if (Build.VERSION.SDK_INT < 23) {
            autoFag = true;
        } else {
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(context, perms)) {
                // Have permissions, do the thing!
                autoFag = true;
            } else {
                // Ask for both permissions
                EasyPermissions.requestPermissions(this, "该功能需要此权限，为了保证应用正常运行!",
                        RC_LOCATION_CONTACTS_PERM, perms);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        if (PackageManager.PERMISSION_GRANTED == grantResults[0]) {
            autoFag = true;
        } else {
            autoFag = false;
        }
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        android.util.Log.d("TAG", "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
// (Optional) Check whether the user denied permissions and checked NEVER ASK AGAIN.
        // This will display a dialog directing them to enable the permission in app settings.
        EasyPermissions.checkDeniedPermissionsNeverAskAgain(this,
                getString(R.string.rationale_ask_again),
                R.string.action_settings, R.string.cancel, null, perms);
    }

    /* 根据uri返回文件路径 */
    public String getPath(Uri uri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        // 好像是android多媒体数据库的封装接口，具体的看Android文档
        Cursor cursor = managedQuery(uri, proj, null, null, null);
        // 按我个人理解 这个是获得用户选择的图片的索引值
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        // 将光标移至开头 ，这个很重要，不小心很容易引起越界
        cursor.moveToFirst();
        // 最后根据索引值获取图片路径
        return cursor.getString(column_index);
    }

    public final static Bitmap lessenUriImage(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回 bm 为空
        options.inJustDecodeBounds = false; // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = (int) (options.outHeight / (float) 320);
        if (be <= 0)
            be = 1;
        options.inSampleSize = be; // 重新读入图片，注意此时已经把 options.inJustDecodeBounds
        // 设回 false 了
        bitmap = BitmapFactory.decodeFile(path, options);
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        System.out.println(w + " " + h); // after zoom
        return bitmap;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (data != null) {
            String fileName = "HeaderImage_" + String.valueOf(System.currentTimeMillis()) + ".png";

            Uri selectImageUri = data.getData();

            if (selectImageUri != null) {
                Uri mDestinationUri = Uri.fromFile(new File(getCacheDir(), fileName));
                UCrop.of(selectImageUri, mDestinationUri).withMaxResultSize(480, 480).withAspectRatio(1, 1).start(NewMyAppSetActivity.this);
            }
            if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
                final Uri resultUri = UCrop.getOutput(data);
                String path = RxPhotoUtils.getRealFilePath(NewMyAppSetActivity.this, resultUri);
                if (path != null) {
                    paths = path;
                    backgroundbitmap = BitmapFactory.decodeFile(path);
                    if (NetUtil.getConnectState(context) != NetUtil.NetWorkState.NONE) {
                        uploadJvBaoContent();
                    } else {
                        alertFailDialog(0);
                    }
                }
            } else if (resultCode == UCrop.RESULT_ERROR) {
                Toast.makeText(context, "图片裁剪失败!", Toast.LENGTH_SHORT).show();
            }
        }

    }

    class HeadImageBackReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String path = intent.getStringExtra("path");
            if (path != null) {
                paths = path;
                backgroundbitmap = BitmapFactory.decodeFile(path);
                if (NetUtil.getConnectState(context) != NetUtil.NetWorkState.NONE) {
                    uploadJvBaoContent();
                } else {
                    alertFailDialog(0);
                }
            }
        }
    }

    private void uploadJvBaoContent() {
        if (NetUtil.getConnectState(context) == NetUtil.NetWorkState.NONE) {
            Toast.makeText(context, "网络异常，请检查网络！", Toast.LENGTH_SHORT).show();
        } else {
            final String imagepath = paths;
            backgroundname = paths.substring(paths.lastIndexOf("/") + 1, paths.length());
            HttpUtils httpUtils = new HttpUtils(10000);
            httpUtils.configCurrentHttpCacheExpiry(5000);
            final ProgressUtil progressUtil = new ProgressUtil();
            progressUtil.ShowProgress(context, true, true, "正在上传......");
            String upImagePath = URLConstants.修改背景图片;
            RequestParams params = new RequestParams();
            params.addBodyParameter("doc", new File(imagepath));
            params.addBodyParameter("id", userId);
            params.addBodyParameter("docFilename", backgroundname);
            httpUtils.send(HttpMethod.POST, upImagePath, params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException e, String msg) {
                            progressUtil.dismiss();
                            Toast.makeText(context, "上传失败！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            progressUtil.dismiss();
                            if (!TextUtils.isEmpty(responseInfo.result)) {
                                Gson gson = new Gson();
                                BackgroundBean bean;
                                try {
                                    bean = gson.fromJson(responseInfo.result, BackgroundBean.class);
                                    if (bean.state.equals("0")) {
                                        member_relative.setImageBitmap(backgroundbitmap);
                                        setResult(1);
                                        UpdateMyMessage();
                                    } else if (bean.state.equals("1")) {
                                        alertFailDialog(1);
                                    } else {
                                        Toast.makeText(context, responseInfo.result, Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JsonSyntaxException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                Toast.makeText(context, "上传失败！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    }

    private void alertFailDialog(int type) {
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.show();
        Window window = builder.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);// 设置生效
        window.setGravity(Gravity.CENTER);
        window.setContentView(R.layout.dialog_alert_ok);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);
        if (type == 0) {
            delete_tv.setText("请检查您的网络！");
        } else {
            delete_tv.setText("头像上传失败！");
        }
        delete_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.cancel();
            }
        });

    }

    private void UpdateMyMessage() {
        // new MyMessageAsync().execute(URLConstants.查询个人信息 + "?uid=" + userId);
        String path = URLConstants.查询个人信息 + "?uid=" + userId;
        StringRequest request = new StringRequest(Request.Method.GET, path,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        if (!TextUtils.isEmpty(s)) {
                            Gson gson = new Gson();
                            try {
                                MyMessageBackBean backBean = gson.fromJson(s,
                                        MyMessageBackBean.class);
                                if (backBean.status == 0) {
                                    MyMessageBean bean = null;
                                    if (backBean.list != null
                                            && backBean.list.size() > 0) {
                                        for (int i = 0; i < backBean.list
                                                .size(); i++) {
                                            bean = backBean.list.get(i);
                                        }
                                        sharedPrefUtil.putString(
                                                context,
                                                ShareFile.USERFILE,
                                                ShareFile.USERBACKGROUNDPATH,
                                                bean.uBackgroundImage);
                                        Intent intent = new Intent(context, DownImageService.class);
                                        intent.setAction("downimage");
                                        intent.putExtra("url", URLConstants.默认背景图片 + "=" + bean.uBackgroundImage);
                                        intent.putExtra("name", bean.uBackgroundImage.replace('/', '0'));
                                        context.startService(intent);
                                        sharedPrefUtil.putString(
                                                context,
                                                ShareFile.USERFILE,
                                                ShareFile.USEREMAIL,
                                                bean.uEmail);
                                        sharedPrefUtil.putString(
                                                context,
                                                ShareFile.USERFILE,
                                                ShareFile.TELEPHONE,
                                                bean.uMobile);
                                        sharedPrefUtil.putString(
                                                context,
                                                ShareFile.USERFILE,
                                                ShareFile.USERID, bean.uId);
                                        sharedPrefUtil.putString(
                                                context,
                                                ShareFile.USERFILE,
                                                ShareFile.USERNAME,
                                                bean.uNickName);
                                        sharedPrefUtil
                                                .putString(context,
                                                        ShareFile.USERFILE,
                                                        ShareFile.U_ACC_NO,
                                                        bean.uAccNo);
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.PERSONREMARK,
                                                bean.uPersontag);
                                        if (!"".equals(bean.uPortrait)) {
                                            String str = bean.uPortrait
                                                    .toString();
                                            str = str.replace("\\", "");
                                            sharedPrefUtil.putString(
                                                    context,
                                                    ShareFile.USERFILE,
                                                    ShareFile.USERPHOTOPATH,
                                                    str);
                                        }
                                    } else {
                                        return;
                                    }
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        } else {
                            return;
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        request.setTag("down");
        request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request);
    }

    /**
     * 图片加载第一次显示监听器
     *
     * @author Administrator
     */
    private static class AnimateFirstDisplayListener extends
            SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                // 是否第一次显示
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    // 图片淡入效果
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }


    private void AlterSet() {
        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            String path = URLConstants.修改用户设置;
            AlterSetAsync(path);
        }
    }

    private void AlterSetAsync(String path) {
        StringRequest request = new StringRequest(Request.Method.POST, path,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();
                                SuccessOrFailBean bean = gson.fromJson(result,
                                        SuccessOrFailBean.class);
                                if (bean.status == 0) {
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> pairs = new HashMap<String, String>();
                pairs.put("tbUserMannge.uid", sharedPrefUtil.getString(context,
                        ShareFile.USERFILE, ShareFile.USERID, "0"));
                pairs.put("tbUserMannge.id", sharedPrefUtil.getString(context,
                        ShareFile.USERFILE, ShareFile.SETID, "0"));
                pairs.put("tbUserMannge.openState", "0");
                pairs.put("tbUserMannge.ringCode", sharedPrefUtil.getString(
                        context, ShareFile.USERFILE, ShareFile.MUSICCODE,
                        "g_88"));
                pairs.put("tbUserMannge.ringDesc", sharedPrefUtil.getString(
                        context, ShareFile.USERFILE, ShareFile.MUSICDESC,
                        "完成任务"));
                pairs.put("tbUserMannge.beforeTime", sharedPrefUtil.getString(
                        context, ShareFile.USERFILE, ShareFile.BEFORETIME, "0"));
                pairs.put("tbUserMannge.morningState", sharedPrefUtil
                        .getString(context, ShareFile.USERFILE,
                                ShareFile.MORNINGSTATE, "0"));
                pairs.put("tbUserMannge.morningTime", sharedPrefUtil.getString(
                        context, ShareFile.USERFILE, ShareFile.MORNINGTIME,
                        "07:58"));
                pairs.put("tbUserMannge.nightState", sharedPrefUtil.getString(
                        context, ShareFile.USERFILE, ShareFile.NIGHTSTATE, "0"));
                pairs.put("tbUserMannge.nightTime", sharedPrefUtil.getString(
                        context, ShareFile.USERFILE, ShareFile.NIGHTTIME,
                        "18:30"));
                pairs.put("tbUserMannge.dayTime", sharedPrefUtil
                        .getString(context, ShareFile.USERFILE,
                                ShareFile.ALLTIME, "23:59"));
                pairs.put("tbUserMannge.dayState", sharedPrefUtil.getString(
                        context, ShareFile.USERFILE, ShareFile.ALLSTATE, "0"));
                return pairs;
            }
        };
        request.setTag("down");
        request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        App.getHttpQueues().cancelAll("down");
        if (headImageBackReceiver != null) {
            context.unregisterReceiver(headImageBackReceiver);
        }
    }

    private void cancleDialog() {
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.show();
        Window window = builder.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_canclefocus);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        delete_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.cancel();
                // App app = App.getDBcApplication();
                Intent intent = new Intent(context, SetDataUpdateActivity.class);
                File file = new File(
                        "/data/data/com.mission.schedule/databases/plan");
                File file1 = new File(Environment.getExternalStorageDirectory()
                        .getPath() + "/YourAppDataFolder/plan");
                // List<Map<String, String>> schList = new
                // ArrayList<Map<String,String>>();
                // List<Map<String, String>> repList = new
                // ArrayList<Map<String,String>>();
                // schList = app.queryAllSchData();
                // repList = app.QueryAllRepData();
                if (file.exists()) {
                    // if(schList!=null&&schList.size()>0){
                    // for(int i=0;i<schList.size();i++){
                    // app.deleteSchData(schList.get(i).get(ScheduleTable.schID));
                    // }
                    // }
                    // if(repList!=null&&repList.size()>0){
                    // for(int i=0;i<repList.size();i++){
                    // app.deleteRepData(repList.get(i).get(CLRepeatTable.repID));
                    // }
                    // }
                    intent.putExtra("type", "0");
                    startActivity(intent);
                } else if (file1.exists() && !file.exists()) {
                    // if(schList!=null&&schList.size()>0){
                    // for(int i=0;i<schList.size();i++){
                    // app.deleteSchData(schList.get(i).get(ScheduleTable.schID));
                    // }
                    // }
                    // if(repList!=null&&repList.size()>0){
                    // for(int i=0;i<repList.size();i++){
                    // app.deleteRepData(repList.get(i).get(CLRepeatTable.repID));
                    // }
                    // }
                    intent.putExtra("type", "1");
                    startActivity(intent);
                } else {
                    alertFailDialog();
                }
            }
        });
        TextView delete_canel = (TextView) window
                .findViewById(R.id.delete_canel);
        delete_canel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.cancel();
            }
        });
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);
        delete_tv.setText("注意\n迁移数据时，所有本地数据将全部清空!");

    }

    private void alertFailDialog() {
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.show();
        Window window = builder.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);// 设置生效
        window.setGravity(Gravity.CENTER);
        window.setContentView(R.layout.dialog_alert_ok);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);
        delete_tv.setText("所需迁移的数据文件不存在！");
        delete_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.cancel();
            }
        });

    }
}
